import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Row, Col, message } from 'antd';
import { PrimaryC, DATA_ENTRY, AdvancedSearch, TableC, ModalC, ContentPackage } from '@/src/components';
import MyModal from './myModal';

@connect(({ couponPoolDefinitionM, institutionConfigurationM, userM: user, couponPoolApprovalM, loading, globalM }) => ({
  couponPoolDefinitionM,
  institutionConfigurationM,
  user,
  couponPoolApprovalM,
  loading: loading.effects['couponPoolDefinitionM/saerchAll'],
  globalM,
}))
export default class CouponPoolDefinition extends PureComponent {
  state = {
    timeOutGap: 500,
    modalVisible: false,
    current: '',
    pageSize: '',
    total: '',
    isEdit: false,
    formDate: {},
    order: '',
    mangement: undefined,
    columnKey: 'createTime',
    currentUser: {},
    sortedInfo: {},
  };

  MyModalRef = React.createRef();

  componentDidMount() {
    const { dispatch } = this.props;
    // 获取用户信息
    dispatch({
      type: 'couponPoolDefinitionM/getUserInfo',
      payload: {
        userId: localStorage.getItem('antd-pro-userId'),
      },
      callback: (res) => {
        this.getManger(res);
        this.setState({
          currentUser: res,
        });
      },
    });
    dispatch({
      type: 'couponPoolApprovalM/getPoolName',
      payload: { pageSize: 20, currentSize: 1 },
    });
    dispatch({
      type: 'couponPoolDefinitionM/getTree',
      payload: {},
    });
    dispatch({
      type: 'institutionConfigurationM/Search',
      payload: {},
    });
    this.fundat();
  }

  // 判断当前用户的岗位信息是否有权限更改公司级部门及券池
  getManger = (currentUser) => {
    const { stationModels } = currentUser;
    let mangement = false;
    stationModels &&
      stationModels.forEach((element) => {
        if (element.id == 'security_pool_manager') {
          mangement = true;
        }
      });
    this.setState({
      mangement,
    });
  };

  // 页面初始化请求数据
  fundat = () => {
    const { dispatch } = this.props;
    const pageInfo = {
      currentPage: 1,
      numInPage: 10,
    };
    dispatch({
      type: 'couponPoolDefinitionM/saerchAll',
      payload: {
        pageInfo,
      },
      callback: (res) => {
        this.setState({
          current: res.currentPage,
          pageSize: res.numInPage,
          total: res.total,
        });
      },
    });
  };

  // 点击查询
  searchData = (e) => {
    const { dispatch } = this.props;
    const { formDate } = this.state;
    const pageInfo = {
      currentPage: 1,
      numInPage: 10,
    };
    const datas = {
      name: formDate.name || '',
      assetClass: formDate.assetClass || [],
      type: formDate.type || [],
      institutions: formDate.institutions || [],
    };
    dispatch({
      type: 'couponPoolDefinitionM/saerchAll',
      payload: {
        name: datas.name,
        assetClass: datas.assetClass,
        type: datas.type,
        institutions: datas.institutions,
        pageInfo,
      },
      callback: (res) => {
        this.setState({
          current: res.currentPage,
          pageSize: res.numInPage,
          total: res.total,
        });
      },
    });
  };

  //  点击新增编辑
  handleAdd = (e) => {
    const { institutionConfigurationM } = this.props;
    const {
      globalM: {
        dataDictionary: { SECURITYPOOL_ASSETCLASS = [], SECURITYPOOL_TYPE = [] },
      },
    } = this.props;
    const data = institutionConfigurationM;
    const selectGroup = {
      data,
      assetClass: SECURITYPOOL_ASSETCLASS,
      type: SECURITYPOOL_TYPE,
    };
    if (!e) {
      this.setState({
        defaultData: e,
        isEdit: false,
        selectGroup,
      });
    } else {
      this.setState({
        defaultData: e,
        isEdit: true,
        selectGroup,
      });
    }
    this.setState({
      modalVisible: true,
    });
  };

  // 点击保存
  handleOk = (e) => {
    e.preventDefault();
    const { dispatch } = this.props;
    const form = this.MyModalRef.current?.FormGroupRefList.current?.formRef.current;
    const { defaultData, isEdit } = this.state;
    const query = isEdit
      ? {
          id: defaultData.id,
          name: form.getFieldValue('name1'),
          assetClass: form.getFieldValue('assetClass1'),
          type: form.getFieldValue('type1'),
          approval: form.getFieldValue('approval') || '',
          institutionId: form.getFieldValue('institutionId1') || [],
          share: form.getFieldValue('share') || '',
        }
      : {
          name: form.getFieldValue('name1'),
          assetClass: form.getFieldValue('assetClass1'),
          type: form.getFieldValue('type1'),
          approval: form.getFieldValue('approval') || '',
          institutionId: form.getFieldValue('institutionId1') || [],
          share: form.getFieldValue('share') || '',
        };
    if (query.name == null || query.assetClass == null || query.type == null) {
      message.warning('请填写完整');
    } else {
      if (query.type == 'institution') {
        if (query.institutionId && query.institutionId.length) {
          if (isEdit) {
            dispatch({
              type: 'couponPoolDefinitionM/editData',
              payload: query,
            }).then((res) => {
              if (res && res.code == 0) {
                this.setState({
                  modalVisible: false,
                });
              } else {
                this.setState({
                  modalVisible: true,
                });
              }
            });
          } else {
            dispatch({
              type: 'couponPoolDefinitionM/addData',
              payload: query,
            }).then((res) => {
              if (res.code == 0) {
                this.setState({
                  modalVisible: false,
                });
              } else {
                this.setState({
                  modalVisible: true,
                });
              }
            });
          }
        } else {
          message.warning('请选择关联部门');
        }
      } else {
        if (isEdit) {
          dispatch({
            type: 'couponPoolDefinitionM/editData',
            payload: query,
          }).then((res) => {
            if (res && res.code == 0) {
              this.setState({
                modalVisible: false,
              });
            } else {
              this.setState({
                modalVisible: true,
              });
            }
          });
        } else {
          dispatch({
            type: 'couponPoolDefinitionM/addData',
            payload: query,
          }).then((res) => {
            if (res.code == 0) {
              this.setState({
                modalVisible: false,
              });
            } else {
              this.setState({
                modalVisible: true,
              });
            }
          });
        }
      }
      this.searchData();
    }
  };

  // 点击取消
  handleCancel = () => {
    this.setState({
      modalVisible: false,
    });
  };

  // 新增modal框
  renderModal = () => {
    const { modalVisible } = this.state;
    const { treeDatas } = this.props.couponPoolDefinitionM;
    const props = {
      ...this.state,
    };
    const modalProps = {
      destroyOnClose: true,
      visible: modalVisible,
      maskClosable: false,
      title: '新增券池',
      width: 450,
      height: 300,
    };
    return (
      <div style={{ marginLeft: '200px' }}>
        <ModalC {...modalProps} onOk={this.handleOk} onCancel={this.handleCancel}>
          <MyModal data={props} onRef={(ref) => (this.MyModalRef.current = ref)} mangement={this.state.mangement} treeDatas={treeDatas} />
        </ModalC>
      </div>
    );
  };

  // 表格页码排序改变事件
  onChangeTable = (pagination, filt, sorter) => {
    const { dispatch } = this.props;
    const { formDate } = this.state;
    const datas = {
      name: formDate.name || '',
      assetClass: formDate.assetClass || [],
      type: formDate.type || [],
      institutions: formDate.institutions || [],
    };
    datas.pageInfo = {
      currentPage: pagination.current,
      numInPage: pagination.pageSize,
    };
    this.setState({
      sortedInfo: sorter,
    });
    if (sorter.order != undefined) {
      if (this.state.current != pagination.current) {
        if ('descend' === this.state.order) {
          if (sorter.columnKey == 'createUserName') {
            datas.sortInfo = {
              sortType: 'DESC',
              sortItem: 'createUserId',
            };
          } else {
            datas.sortInfo = {
              sortType: 'DESC',
              sortItem: sorter.columnKey,
            };
          }
        } else {
          if (sorter.columnKey == 'createUserName') {
            datas.sortInfo = {
              sortType: 'ASC',
              sortItem: 'createUserId',
            };
          } else {
            datas.sortInfo = {
              sortType: 'ASC',
              sortItem: sorter.columnKey,
            };
          }
        }
      } else {
        if ('descend' === this.state.order) {
          if (sorter.columnKey == 'createUserName') {
            datas.sortInfo = {
              sortType: 'ASC',
              sortItem: 'createUserId',
            };
            this.setState({
              order: 'ascend',
            });
          } else {
            datas.sortInfo = {
              sortType: 'ASC',
              sortItem: sorter.columnKey,
            };
            this.setState({
              order: 'ascend',
            });
          }
        } else {
          if (sorter.columnKey == 'createUserName') {
            datas.sortInfo = {
              sortType: 'DESC',
              sortItem: 'createUserId',
            };
            this.setState({
              order: 'descend',
            });
          } else {
            datas.sortInfo = {
              sortType: 'DESC',
              sortItem: sorter.columnKey,
            };
            this.setState({
              order: 'descend',
            });
          }
        }
      }
    }

    dispatch({
      type: 'couponPoolDefinitionM/saerchAll',
      payload: datas,
      callback: (res) => {
        this.setState({
          current: res.currentPage,
          pageSize: res.numInPage,
          total: res.total,
        });
      },
    });
  };

  // 资产类别转义
  getValueById = (e) => {
    const {
      globalM: {
        dataDictionary: { SECURITYPOOL_ASSETCLASS = [] },
      },
    } = this.props;
    const assetClass = SECURITYPOOL_ASSETCLASS;
    let text = '';
    assetClass
      ? assetClass.map((item) => {
          if (item.code == e) {
            text = item.value;
          }
        })
      : null;
    return text;
  };

  // 券池类型转义
  getValueById1 = (e) => {
    const {
      globalM: {
        dataDictionary: { SECURITYPOOL_TYPE = [] },
      },
    } = this.props;
    const type = SECURITYPOOL_TYPE;
    let text = '';
    type
      ? type.map((item) => {
          if (item.code == e) {
            text = item.value;
          }
        })
      : null;
    return text;
  };

  // 是否公开转义
  changeShare = (text, record) => {
    let str = '';
    if (record.type == 'tenant' || record.type == 'institution') {
      str = '--';
    } else {
      if (text == true) {
        str = '是';
      } else if (text == false) {
        str = '否';
      }
    }
    return str;
  };

  // 关联部门转义
  changeInstitu = (text, record) => {
    let str = '';
    if (record.type == 'tenant') {
      str = '--';
    } else if (record.type == 'user') {
      if (record.share == true) {
        str = text;
      } else if (record.share == false) {
        str = '--';
      }
    } else {
      str = text;
    }
    return str;
  };

  // 是否审批转义
  chooseShow = (text, record) => {
    let str = '';
    if (record.type == 'user') {
      str = '--';
    } else {
      if (record.approval == false) {
        str = '否';
      } else if (record.approval == true) {
        str = '是';
      } else {
        str = '--';
      }
    }
    return str;
  };

  showTable = () => {
    const { couponPoolDefinitionM, loading } = this.props;
    const { tableData } = couponPoolDefinitionM;
    const { sortedInfo } = this.state;
    const { dataSource } = tableData;
    const columns = [
      {
        title: '券池名称',
        dataIndex: 'name',
        key: 'name',
        sorter: true,
      },
      {
        title: '资产类别',
        dataIndex: 'assetClass',
        key: 'assetClass',
        width: '140px',
        sorter: true,
        sortOrder: sortedInfo.columnKey === 'assetClass' && sortedInfo.order,
        render: (text, record) => {
          return text === undefined ? '--' : this.getValueById(text);
        },
      },
      {
        title: '券池类型',
        dataIndex: 'type',
        key: 'type',
        sorter: true,
        sortOrder: sortedInfo.columnKey === 'type' && sortedInfo.order,
        render: (text, record) => {
          return this.getValueById1(text);
        },
      },
      {
        title: '是否审批',
        dataIndex: 'approval',
        key: 'approval',
        sorter: true,
        sortOrder: sortedInfo.columnKey === 'approval' && sortedInfo.order,
        render: (text, record) => {
          return this.chooseShow(text, record);
        },
      },
      {
        title: '关联部门',
        dataIndex: 'institution',
        key: 'institution',
        render: (text, record) => {
          return this.changeInstitu(text, record);
        },
      },
      {
        title: '是否公开',
        dataIndex: 'share',
        key: 'share',
        sorter: true,
        sortOrder: sortedInfo.columnKey === 'share' && sortedInfo.order,
        render: (text, record) => {
          return this.changeShare(text, record);
        },
      },
      {
        title: '创建日期',
        dataIndex: 'createTime',
        key: 'createTime',
        sorter: true,
        sortOrder: sortedInfo.columnKey === 'createTime' && sortedInfo.order,
      },
      {
        title: '创建人',
        dataIndex: 'createUserName',
        key: 'createUserName',
        sorter: true,
        sortOrder: sortedInfo.columnKey === 'createUserName' && sortedInfo.order,
      },
      {
        title: '操作',
        dataIndex: 'id',
        key: 'id',
        type: 'operate',
        operates: [
          {
            title: '编辑',
            onClick: (record, index) => {
              this.handleAdd(record);
            },
            rules: {
              disabled: this.state.mangement
                ? { items: [{ key: 'edit', value: [false], relation: ['='] }], relation: 'or' }
                : {
                    items: [
                      { key: 'type', value: ['user'], relation: ['!='] },
                      { key: 'edit', value: [false], relation: ['='] },
                    ],
                    relation: 'or',
                  },
            },
          },
          {
            title: '删除',
            onClick: (record, index) => {
              this.deletePool(record.id);
            },
            rules: {
              disabled: this.state.mangement
                ? { items: [{ key: 'delete', value: [false], relation: ['='] }], relation: 'or' }
                : {
                    items: [
                      { key: 'type', value: ['user'], relation: ['!='] },
                      { key: 'delete', value: [false], relation: ['='] },
                    ],
                    relation: 'or',
                  },
            },
          },
        ],
      },
    ];

    return (
      <div style={{ marginTop: '10px' }}>
        <Row>
          <Col>
            <PrimaryC title='新增' style={{ margin: '10px' }} onClick={() => this.handleAdd()} />
          </Col>
        </Row>
        <TableC
          columns={columns}
          loading={loading}
          dataSource={dataSource}
          current={this.state.current}
          pageSize={this.state.pageSize}
          total={this.state.total}
          rowKey='id'
          selfScrollY={true}
          pagination={true}
          onChange={this.onChangeTable}
        />
      </div>
    );
  };

  // 删除响应
  deletePool = (id) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'couponPoolDefinitionM/deleteData',
      payload: { id },
    }).then((res) => {
      if (res && res.code == 0) {
        message.success('删除成功');
        this.searchData();
      } else {
        message.error(res ? res.msg : '删除失败');
      }
    });
  };

  // 券池名称下拉框输入事件
  couponPoolSearch = (e) => {
    const pageInfo = {
      currentPage: 1,
      numInPage: 20,
    };
    const { timeOutGap } = this.state;
    const { dispatch } = this.props;
    this.timer ? clearTimeout(this.timer) : '';
    this.timer = setTimeout(() => {
      dispatch({
        type: 'couponPoolApprovalM/getPoolName',
        payload: {
          name: e,
          pageInfo,
        },
      });
    }, timeOutGap);
  };

  // 转换券池名称格式
  onChangeNameType = (e) => {
    const nameSelect = [];
    if (e && e.length) {
      e.map((item) => {
        nameSelect.push({
          title: item.name,
          value: item.name,
        });
      });
      return nameSelect;
    }
  };

  // 资产类别下拉数据转换
  onChangeassetClass = (e) => {
    const arr = e.SECURITYPOOL_ASSETCLASS;
    const assetClass = [];
    if (arr && arr.length) {
      arr.map((item) => {
        assetClass.push({
          title: item.value,
          value: item.code,
        });
      });
      return assetClass;
    }
  };

  // 券池类型下拉数据转换
  onChangeType = (e) => {
    const arr = e.SECURITYPOOL_TYPE;
    const type = [];
    if (arr && arr.length) {
      arr.map((item) => {
        type.push({
          title: item.value,
          value: item.code,
        });
      });
      return type;
    }
  };

  // 转换关联部门
  onChangein = (e) => {
    const institutions = [];
    if (e && e.length) {
      e.map((item) => {
        institutions.push({
          title: item.instName,
          value: item.id,
        });
      });
      return institutions;
    }
  };

  nameChange = (e) => {
    if (e == undefined) {
      this.props.dispatch({
        type: 'couponPoolApprovalM/getPoolName',
        payload: { pageSize: 20, currentSize: 1 },
      });
    }
  };

  render() {
    const {
      globalM: { dataDictionary },
      couponPoolDefinitionM: { treeDatas },
      couponPoolApprovalM: { poolNameData },
    } = this.props;
    const nameSelect = this.onChangeNameType(poolNameData);
    const assetClass = this.onChangeassetClass(dataDictionary);
    const type = this.onChangeType(dataDictionary);
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'name',
          title: '券池名称',
          type: DATA_ENTRY.SELECT,
          dataSource: nameSelect,
          showSearch: true,
          allowClear: true,
          onSearch: (e) => {
            this.couponPoolSearch(e);
          },
          onChange: (e) => {
            this.nameChange(e);
          },
        },
        {
          dataIndex: 'assetClass',
          title: '资产类别',
          type: DATA_ENTRY.SELECT,
          dataSource: assetClass,
          isMultiple: true,
          allowClear: true,
        },
        {
          dataIndex: 'type',
          title: '券池类型',
          type: DATA_ENTRY.SELECT,
          dataSource: type,
          isMultiple: true,
          allowClear: true,
        },
        {
          dataIndex: 'institutions',
          title: '关联部门',
          type: DATA_ENTRY.TREESELECT,
          dataSource: treeDatas,
          isMultiple: true,
          allowClear: true,
        },
      ],
      onQuery: (e) => {
        this.setState(
          {
            formDate: e,
          },
          () => this.searchData(),
        );
      },
      onClear: () => {},
    };

    return (
      <ContentPackage
        title='券池定义'
        contentHtml={
          <div>
            <div className='bondDeviation'>
              <div>
                <AdvancedSearch {...searchProps} />
              </div>
              {this.showTable()}
            </div>
            <div> {this.renderModal()} </div>
          </div>
        }
      />
    );
  }
}
